<script lang="ts" setup>
import { ControlsCard, SearchCard } from '@/components/basic/Card'
import { Group } from '@/components/basic/Loading'
import { Pagination } from '@/components/basic/Pagination'
import { UploadAudio, UploadImage, UploadVideo } from '@/components/basic/Upload'
import { List, ListItem, Tag, TaskList } from '@/components/business/ai/virtual'
import { SvgIcon } from '@/components/basic/icon'


import Api from '@/api/'
import to from '@/utils/awaitTo'
import { reactive, ref } from 'vue'
import { message } from 'ant-design-vue'
import { cloneDeep } from 'lodash-es'


const initData = {
  affiliatedPlatform: '',
  digitalHumanName: '',
  digitalHumanId: '',
  userId: undefined,
  affiliatedTiktokId: '',
  digitalHumanCode: '',
  digitalHumanStatus: '',
  previewDemo: '',
  iconUrl: ''
}

const formRef = ref()
const queryRef = ref()
const queryParams = reactive({
  pageNum: 1,
  pageSize: 30,
  digitalHumanName: '',
  affiliatedTiktokName: '',
  status: '',
  affiliatedPlatform: undefined
})
const form = ref(initData)
const list = ref([])
const dockerList = ref([])
const total = ref(0)
const open = ref(false)
const tikTokLoading = ref(false)
const tiktokList = ref([])
const title = ref('')
const totalNumber = ref(0)
const loading = ref(false)

// 规则
const rules = {
  digitalHumanName: [{ required: true, message: '请输入用户名称', trigger: ['blur', 'change'] }],
  affiliatedTiktokId: [{ required: true, message: '请输入抖音号', trigger: ['blur', 'change'] }],
  digitalHumanCode: [{ required: true, message: '请输入抖音号', trigger: ['blur', 'change'] }],
  digitalHumanStatus: [{ required: true, message: '请选择状态', trigger: ['blur', 'change'] }],
  userId: [{ required: true, message: '请选择医生', trigger: ['blur', 'change'] }],
  affiliatedPlatform: [{ required: true, message: '请选择平台', trigger: ['blur', 'change'] }]
}

// 列表
const getList = async () => {
  loading.value = true
  const [error, data] = await to(Api.virtual.virtualList(queryParams))
  loading.value = false
  if (!error) {
    list.value = data.rows
    total.value = Number(data.total)
  }
}

// 医生列表
const doctorParams = reactive({
  pageNum: 1,
  pageSize: 1000,
  roleIdentifying: 1,
  nickName: ''
});
const getDockerList = async () => {
  const [error, data] = await to(Api.virtual.virtualEchoDoctorList(doctorParams))
  if (!error) {
    // console.log(data)
    dockerList.value = data
  }
}

// 上线总数量
const getVirtualTotal = async () => {
  const [error, data] = await to(Api.virtual.virtualTotal({ time: new Date().getTime() }))
  if (!error) {
    totalNumber.value = data
  }
}


// 新增数智人
const handleAddHomoSapiens = () => {
  reset()
  open.value = true
  title.value = `新增数智人`
}


// 提交事件
const handleSubmit = (formEl) => {
  if (!formEl) return
  formEl.validate().then(async (values) => {
    const params = Object.assign({}, form.value, values)
    console.log(params)


    /** 修改start */
    if (params.digitalHumanId) {
      const [error, data] = await to(Api.virtual.virtualEditHuman(params))
      if (!error) {
        console.log(data)
        open.value = false
        message.success(`修改数智人成功`)
        await getList()
      }
    }
      /** 修改end */

    /** 新增start */
    else {
      const formData = new FormData()
      formData.append('userId', params.userId)
      formData.append('affiliatedPlatform', params.affiliatedPlatform)
      formData.append('digitalHumanName', params.digitalHumanName)
      formData.append('affiliatedTiktokId', params.affiliatedTiktokId)
      formData.append('digitalHumanStatus', params.digitalHumanStatus)
      formData.append('digitalHumanCode', params.digitalHumanCode)
      formData.append('iconUrl', params.iconUrl)
      formData.append('previewDemo', params.previewDemo)
      const [error] = await to(Api.virtual.virtualAddHuman(formData))
      if (!error) {
        open.value = false
        message.success(`新增数智人成功`)
        await getList()
      }
    }
    /** 新增end */


  })
}

//抖音号确定
const handleChange = async (id: string) => {
  await getTikTokList(id)
}

// 抖音号搜索
const handleSearch = (val: string) => {
  if (val) {
    const DeepClone = cloneDeep(dockerList.value)
    dockerList.value = DeepClone.filter((item: any) => {
      console.log(item.nickName.indexOf(val))
      if (item.nickName.indexOf(val) >= 0) {
        return true
      }
    })
  } else {
    getDockerList()
  }
}

// 修改信息
const handleEdit = async (item) => {
  reset()
  await getTikTokList(item.transcribeUserId)
  form.value = cloneDeep(item)
  title.value = '修改数智人'
  open.value = true
  form.value.userId = item.transcribeUserId
}

// 回显抖音号列表
const getTikTokList = async (doctorUserId: string) => {
  tikTokLoading.value = true
  const [error, data] = await to(Api.virtual.virtualEchoHuman({ doctorUserId }))
  tikTokLoading.value = false
  if (!error) {
    tiktokList.value = data
  }
}


// 搜索事件
const handleQuery = () => {
  getList()
}

// 重置事件
const handleReset = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
  getList()
}

// 重置
const reset = () => {
  form.value = { ...initData }
}


/** 数智人声音创建 */

const SoundCreationRef = ref()
const SoundCreationData = reactive({
  open: false,
  title: '',
  loading: false,
  activeKey: '0',
  list: [],
  timbreList: [],
  timbreParams: {
    timbreReproductionName: '',
    timbreReproductionStatus: '',
    userId: ''
  },
  timbreTotal: 0,
  form: {},
  rules: {
    auOrTe: [
      {
        required: true,
        message: '请选择驱动类型',
        trigger: ['blur', 'change']
      }
    ],
    taskName: [
      {
        required: true,
        message: '请输入任务名称',
        trigger: ['blur', 'change']
      }
    ],
    speedRatio: [
      {
        required: true,
        message: '请输入语速',
        trigger: ['blur', 'change']
      }
    ],
    timbreReproductionId: [
      {
        required: true,
        message: '请选择音色复刻',
        trigger: ['blur', 'change']
      }
    ],
    data: [
      {
        required: true,
        message: '请输入音频/文字',
        trigger: ['blur', 'change']
      }
    ]
  }
})

// 点击事件
const handleSoundCreation = (item) => {
  console.log(item)
  SoundReset()

  SoundCreationData.open = true
  SoundCreationData.title = item.digitalHumanName

  // form表单
  SoundCreationData.form.digitalHumanId = item.digitalHumanId
}

// 创建声音提交
const handleSoundCreationSubmit = () => {
  // console.log(SoundCreationData.form)
  SoundCreationRef.value.validate().then(async (values) => {
    const params = Object.assign({}, SoundCreationData.form, values)
    SoundCreationData.loading = true
    const [error, data] = await to(Api.virtual.virtualCreateTask(params))
    SoundCreationData.loading = false
    if (!error) {
      console.log(data)
      SoundCreationData.open = false
      message.success('创建成功')
      await getVirtualHumanTask()
    }
  })
}

// 创建列表
const getVirtualHumanTask = async () => {
  const [error, data] = await to(Api.virtual.virtualHumanTask({ time: new Date().getTime() }))
  if (!error) {
    SoundCreationData.list = data
  }
}

// 音色复刻列表
const getListOfTimbreReprintsList = async () => {
  const [error, data] = await to(Api.virtual.virtualReproductionList(SoundCreationData.timbreParams))
  if (!error) {
    console.log(data.rows)
    console.log(data.total)
    SoundCreationData.timbreList = data.rows
    SoundCreationData.timbreTotal = Number(data.total)
  }
}

// 音色复刻搜索
const handleReproductionSearch = (value: string) => {
  SoundCreationData.timbreParams.timbreReproductionName = value
  getListOfTimbreReprintsList()
}


// 重置
const SoundReset = () => {
  SoundCreationData.form = {
    auOrTe: '', //音频驱动 1 / 文字驱动 2
    data: '', //音频 / 文字
    digitalHumanId: '', //数字人id
    speedRatio: '', //语速
    taskName: '', //任务名称
    timbreReproductionId: '' //音色复刻id
  }
}

/** 操作字典 */
const OperationDict = [
  {
    label: '制作视频',
    key: '1',
    icon: 'make-video'
  }
]

/** 数智人分类字典 */
const AffiliatedPlatformDict = [
  {
    label: '火山',
    value: '2001',
    color: 'cyan'
  },
  {
    label: '腾讯',
    value: '2002',
    color: 'blue'
  }
]

/** 数智人状态 */
const DigitalTypeDict = [
  {
    label: '未采集',
    value: '1001'
  },
  {
    label: '训练中',
    value: '1002'
  },
  {
    label: '已上线',
    value: '1003'
  }
]

/** 驱动字典 */
const DriverDictionaryDict = [
  {
    label: '文字驱动',
    value: '2'
  },
  {
    label: '音频驱动',
    value: '1'
  }
]

getList()
getDockerList()
getVirtualTotal()
getVirtualHumanTask()
getListOfTimbreReprintsList()
</script>

<template>
  <div>
    <!-- 搜索 -->
    <SearchCard>
      <a-form ref="queryRef" :model="queryParams" layout="inline">
        <a-form-item label="数智人" name="digitalHumanName">
          <a-input v-model:value="queryParams.digitalHumanName" placeholder="请输入用户名称" />
        </a-form-item>
        <a-form-item label="抖音号" name="affiliatedTiktokName">
          <a-input v-model:value="queryParams.affiliatedTiktokName" placeholder="请输入抖音号" />
        </a-form-item>
        <a-form-item label="状态" name="status">
          <a-radio-group
            v-model:value="queryParams.status"
            button-style="solid"
            @change="getList"
          >
            <a-radio-button
              v-for="item in DigitalTypeDict"
              :key="item.value"
              :value="item.value"
            >{{ item.label }}
            </a-radio-button>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="平台" name="affiliatedPlatform">
          <a-select v-model:value="queryParams.affiliatedPlatform" :options="AffiliatedPlatformDict"
                    placeholder="请选择"
                    style="width: 100px;" @change="getList" />
        </a-form-item>
        <a-form-item>
          <a-space :size="12">
            <a-button type="primary" @click="handleQuery">确定</a-button>
            <a-button @click="handleReset(queryRef)">重置</a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </SearchCard>

    <!-- 操作-->
    <ControlsCard>
      <a-button type="primary" @click="handleAddHomoSapiens">新增数智人</a-button>
      <a-button danger type="primary">已上线 {{ totalNumber }}</a-button>
    </ControlsCard>

    <!-- 数智人制作任务列表 -->
    <a-collapse v-if="SoundCreationData.list.length" v-model:activeKey="SoundCreationData.activeKey"
                class="mb-3" collapsible="header">
      <a-collapse-panel key="1">
        <template #header>
          <div>数智人制作任务列表 {{ SoundCreationData.list.length }}个</div>
        </template>
        <div class="flex flex-wrap">
          <TaskList v-for="(item,index) in SoundCreationData.list" :key="index" :item="item" />
        </div>
      </a-collapse-panel>
    </a-collapse>

    <!-- 列表 -->
    <Group :is-empty="!list.length" :pending="loading">
      <List>
        <ListItem v-for="(item,index) in list" :key="index" :item="item">
          <!-- 标签 -->
          <template #tag>
            <Tag :digitalHumanStatus="item.digitalHumanStatus" />
          </template>

          <!-- 修改 -->
          <template #edit>
            <SvgIcon class="cursor-pointer" name="edit" type="svg" @click="handleEdit(item)" />
          </template>

          <!--  底部图片 -->
          <template #bottom="{row}">
            <a-dropdown placement="bottomLeft">
              <div class="absolute right-0 bottom-0">
                <SvgIcon name="more" type="svg" />
              </div>
              <template #overlay>
                <a-menu>
                  <a-menu-item
                    v-for="(record) in OperationDict"
                    :key="record.key" @click="handleSoundCreation(row)"
                  >
                    {{ record.label }}

                    <template #icon>
                      <SvgIcon :name="record.icon" type="svg" />
                    </template>
                  </a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>
          </template>
        </ListItem>

        <!-- 分页 -->
        <template #pagination>
          <Pagination v-model:page-num="queryParams.pageNum" v-model:page-size="queryParams.pageSize" :total="total"
                      @pagination="getList()" />
        </template>
      </List>
    </Group>


    <!-- 表单 -->
    <a-modal v-model:open="open" :title="title" @ok="handleSubmit(formRef)">
      <a-form ref="formRef" :model="form" :rules="rules" layout="vertical">
        <a-form-item label="头像" name="iconUrl">
          <UploadImage v-model="form.iconUrl" />
        </a-form-item>

        <a-form-item label="选择平台" name="affiliatedPlatform">
          <a-radio-group
            v-model:value="form.affiliatedPlatform"
            button-style="solid"
          >
            <a-radio-button
              v-for="item in AffiliatedPlatformDict"
              :key="item.value"
              :value="item.value"
            >{{ item.label }}
            </a-radio-button
            >
          </a-radio-group>
        </a-form-item>

        <a-form-item label="数智人名称" name="digitalHumanName">
          <a-input
            v-model:value="form.digitalHumanName"
            :disabled="!!form.digitalHumanId"
            placeholder="请输入数智人哦"
          />
        </a-form-item>

        <a-form-item label="选择医生" name="userId">
          <a-select
            v-model:value="form.userId"
            :default-active-first-option="false"
            :field-names="{ label: 'nickName', value: 'userId' }"
            :filter-option="false"
            :not-found-content="null"
            :options="dockerList"
            :show-arrow="false"
            placeholder="请搜索医生"
            show-search
            @change="handleChange"
            @search="handleSearch"
          >
          </a-select>
        </a-form-item>

        <a-form-item v-if="tiktokList && tiktokList.length" label="抖音号" name="affiliatedTiktokId">
          <a-spin v-if="tikTokLoading" />
          <a-radio-group v-else v-model:value="form.affiliatedTiktokId">
            <a-space wrap>
              <a-radio
                v-for="item in tiktokList"
                :key="item.tiktokId"
                :value="item.tiktokId"
              >{{ item.uniqueName }}
              </a-radio>
            </a-space>
          </a-radio-group>
        </a-form-item>

        <a-form-item label="数智人编号" name="digitalHumanCode">
          <a-input v-model:value="form.digitalHumanCode" placeholder="请输入数智人编号" />
        </a-form-item>

        <a-form-item label="选择状态" name="digitalHumanStatus">
          <a-radio-group
            v-model:value="form.digitalHumanStatus"
            button-style="solid"
          >
            <a-radio-button
              v-for="item in DigitalTypeDict"
              :key="item.value"
              :value="item.value"
            >{{ item.label }}
            </a-radio-button>
          </a-radio-group>
        </a-form-item>

        <a-form-item v-if="Number(form.digitalHumanStatus) === 1003" label="预览视频" name="previewDemo">
          <UploadVideo v-model="form.previewDemo" />
        </a-form-item>

      </a-form>
    </a-modal>

    <!-- 创建表单 -->
    <a-modal v-model:open="SoundCreationData.open" :ok-button-props="{loading: SoundCreationData.loading}"
             :title="SoundCreationData.title"
             @ok="handleSoundCreationSubmit">
      <a-form ref="SoundCreationRef" :model="SoundCreationData.form" :rules="SoundCreationData.rules" layout="vertical">
        <a-form-item label="驱动" name="auOrTe">
          <a-radio-group v-model:value="SoundCreationData.form.auOrTe" button-style="solid">
            <a-radio-button v-for="(item,index) in DriverDictionaryDict" :key="index" :value="item.value">{{ item.label
              }}
            </a-radio-button>
          </a-radio-group>
        </a-form-item>

        <a-form-item label="任务名称" name="taskName">
          <a-input v-model:value="SoundCreationData.form.taskName" />
        </a-form-item>

        <a-form-item v-if="Number(SoundCreationData.form.auOrTe) === 2" label="语速(倍数)" name="speedRatio">
          <!--          <a-select v-model:value="SoundCreationData.form.speedRatio" :options="PaceDict" />-->
          <a-input v-model:value="SoundCreationData.form.speedRatio" placeholder="请输入倍数" />
        </a-form-item>

        <a-form-item v-if="Number(SoundCreationData.form.auOrTe) === 2" label="音色复刻" name="timbreReproductionId">
          <a-select
            v-model:value="SoundCreationData.form.timbreReproductionId"
            :fieldNames="{label:'timbreReproductionName',value:'timbreReproductionId'}"
            :options="SoundCreationData.timbreList"
            :showSearch="true"
            placeholder="请选择音色复刻"
            @search="handleReproductionSearch"
          />
        </a-form-item>

        <a-form-item v-if="Number(SoundCreationData.form.auOrTe) === 1" label="语言" name="data">
          <UploadAudio v-model="SoundCreationData.form.data" />
        </a-form-item>

        <a-form-item v-if="Number(SoundCreationData.form.auOrTe) === 2" label="语言" name="data">
          <a-input v-model:value="SoundCreationData.form.data" />
        </a-form-item>

      </a-form>
    </a-modal>
  </div>
</template>

<style lang="less" scoped>

</style>
